package com.leetcode.LeetCode精选TOP面试题;

/**
 * @author 覃国强
 * @date 2022-05-11 14:23
 */
public class 题库_0008_字符串转换整数atoi {

  public static void main(String[] args) {
    System.out.println(Integer.MIN_VALUE);
    System.out.println(Integer.MAX_VALUE);
    System.out.println((int)'0');
    System.out.println((int)'9');
  }

  static
  class Solution {
    public int myAtoi(String s) {
      if (s == null || s.length() == 0) {
        return 0;
      }
      State state = new State();
      for (char ch : s.toCharArray()) {
        if (state.isEnd) {
          break;
        }
        state.next(ch);
      }
      return state.getAnswer();
    }

    static class State {

      boolean isEnd = false;
      boolean isLeadingSpace = true;
      boolean isSymbol = true;
      boolean isOverflow = false;
      boolean isPositive = true;
      int answer = 0;

      public void next(char ch) {
        if (isEnd) {
          return;
        }
        // 前导空格
        if (isLeadingSpace && ch == ' ') {
          return;
        }
        // 符号位
        if (isSymbol && (ch == '-' || ch == '+')) {
          isPositive = ch == '+';
          isSymbol = false;
          isLeadingSpace = false;
          return;
        }
        // 非数字
        if (!Character.isDigit(ch)) {
          isEnd = true;
          return;
        }
        // 数字
        isLeadingSpace = false;
        isSymbol = false;
        int num = ch - '0';
        //// 溢出
        if (answer > Integer.MAX_VALUE / 10) {
          isOverflow = true;
          isEnd = true;
          return;
        }
        //// 溢出边界
        if (answer == Integer.MAX_VALUE / 10) {
          if ((isPositive && num >= 7) || (!isPositive && num >= 8)) {
            isOverflow = true;
            isEnd = true;
            return;
          }
        }
        //// 正常范围
        answer = answer * 10 + num;
      }

      public int getAnswer() {
        if (isOverflow) {
          return isPositive ? Integer.MAX_VALUE : Integer.MIN_VALUE;
        }
        return isPositive ? answer : -1 * answer;
      }
    }
  }

}
